package com.suxin.logger.handler;

import com.suxin.logger.Level;
import com.suxin.logger.LogRecord;
import com.suxin.logger.formatter.Formatter;
import com.suxin.logger.formatter.SimpleFormatter;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

/**
 * @author Tang
 * @classname StreamHandler
 * @description [  ]
 * @date 2022/4/26 22:10
 */
public class StreamHandler extends Handler {

    private OutputStream output;

    // OutputStream 流的包装
    private Writer writer;

    private void configure() {
        setLevel(Level.INFO);
        setFormatter(new SimpleFormatter());
        setFilter(null);
    }

    public StreamHandler() {
        configure();
    }

    public StreamHandler(OutputStream output, Formatter formatter) {
        configure();
        setFormatter(formatter);
        setOutput(output);
    }

    @Override
    public void publish(LogRecord lr) {
        if (!isLoggable(lr)) {
            return;
        }
        String msg;
        msg = getFormatter().format(lr);
        try {
            this.writer.write(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void flush() {
        try {
            this.writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void close() {
        try {
            this.writer.flush();
            this.writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    public boolean isLoggable(LogRecord lr) {
        if (writer == null || lr == null) {
            return false;
        }
        return super.isLoggable(lr);
    }

    public OutputStream getOutput() {
        return output;
    }

    public void setOutput(OutputStream output) {
        this.output = output;
        this.writer = new OutputStreamWriter(output);
    }
}